library(tidyverse)
## ── Attaching packages ────── tidyverse 1.3.0 ──
## ✓ ggplot2 3.3.2     ✓ purrr   0.3.4
## ✓ tibble  3.0.3     ✓ dplyr   1.0.0
## ✓ tidyr   1.1.0     ✓ stringr 1.4.0
## ✓ readr   1.3.1     ✓ forcats 0.5.0
## ── Conflicts ───────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
emission <- read.csv("/Users/stephenwang/Desktop/Academics /STA 313/313 final project/emission_data.csv")
temp <- read.csv("/Users/stephenwang/Desktop/Academics /STA 313/313 final project/GlobalTemperatures.csv")

emission <- filter(emission, Country=="World")
emission <- t(emission)
emission <- data.frame(r1=row.names(emission),emission, row.names = NULL)
x<-substr(emission$r1,2,5)
emission <- emission%>%mutate(Year=x)
emission <- emission[-1,]


y <- substr(temp$dt, 1, 4)
temp <- temp %>% mutate(Year = y)

wrd_em<-emission %>% filter(Year>=1960 & Year<=2015)
wrd_temp<-temp %>% group_by(Year) %>% summarise(temperature=sum(LandAverageTemperature))%>%filter(Year>=1960)
## `summarise()` ungrouping output (override with `.groups` argument)
wrd_temp <-wrd_temp %>% mutate (annual_avg_temp = temperature/12)

wrd_em$Year=as.numeric(wrd_em$Year)
wrd_temp$Year=as.numeric(wrd_temp$Year)
wrd_em$emission=as.numeric(wrd_em$emission)

temp_vs_em <-right_join(wrd_em,wrd_temp,by="Year")
plot_ly(temp_vs_em, x = ~Year, y = ~annual_avg_temp, type = "scatter", name = "Temperature", mode = "lines") %>%
  layout(yaxis = list(title = "Annual Average Temperature (Celcius)")) %>%
  add_trace(x = ~Year, y = ~emission, mode = "lines", yaxis = "y2", name = "CO2 Emmision") %>%
  layout(yaxis2 = list(overlaying = "y", side = "right",title = "CO2 Emmision (Tons)"),title = "Temperature vs Emmision")